<template>
  <div id="home" class="model-page bgF5">
    <input type="hidden" :value="userid" />
    <div class="page-full-home pBtm">
      <!-- 顶部 -->
      <topHeader :show-left="false" :show-right="true" title="吉命易测">
        <template v-slot:right>
          <span class="c_icon c_msg" @click="toMsgCenter()">
            <i v-if="msgCount&&msgCount!=0">{{msgCount}}</i>
          </span>
        </template>
      </topHeader>
      <!--
        总体说明：
        1.轮播、热门问题、开运宝典如何跳转？
          若是轮播、热门问题：
            若opentype==1,配置为链接(link),跳转至链接
            若opentype==2,配置为富文本(link),跳转至infoDetail路由
          若是开运宝典：
            无需考虑opentype,均跳转至infoDetail路由

        2.跳转至infoDetail路由时如何传参？
          若是轮播。参数为：type=1,id=xxxx
          若是热门问题。参数为：type=3,id=xxxx
          若是开运宝典。参数为：type=2,id=xxxx .
          注：id为文章id
      -->
      <!-- 轮播 -->
      <swiper
        v-if="fetch_data.banner"
        class="banner_wrapper"
        auto
        dots-class="banner-icons"
        dots-position="center"
        :show-dots="showDots"
        :interval="swiperDuration"
      >
        <swiper-item
          class="swiper-demo-img"
          v-for="(i, idx) in fetch_data.banner"
          :key="'banner'+idx"
        >
          <img v-if="i.imgurl&&i.opentype==1" @click="toLink(i.link)" :src="imgUrl(i.imgurl)" alt />
          <img v-else @click="toInfoDetail(1,i.id)" :src="imgUrl(i.imgurl)" alt />
        </swiper-item>
      </swiper>

      <!-- 产品图例 -->
      <ul class="nav_wrapper">
        <li v-for="(i,idx) in fetch_data.product" :key="'nav'+idx" @click="toLink(i.link, idx)">
          <dl>
            <dt>
              <img class="icon" v-if="i.imgurl" :src="imgUrl(i.imgurl)" :alt="i.titlename" />
              <img class="sign" v-if="i.hotspotimg" :src="imgUrl(i.hotspotimg)" :alt="i.titlename" />
            </dt>
            <dd>{{i.titlename}}</dd>
          </dl>
        </li>
      </ul>

      <!-- 今日运势 -->
      <div class="today_luck_wrapper">
        <div class="mTitle">今日运势</div>

        <div class="content">
          <p class="c_time" @click="toJrys">
            <i></i>
            {{getDate()}}
          </p>
          <div class="c_poit" @click="toJrys">
            <!-- <roundCircle :progress="progress" :progress1="progress1" :progress2="progress2" :progress3="progress3"></roundCircle> -->
            <roundCircle v-model="refleshCircle"></roundCircle>
          </div>
          <ul class="c_pro">
            <li
              v-for="(i,idx) in tody_pro_list"
              :key="'today_'+idx"
              @click="toNavgate(i.pathIndex, idx)"
            >
              <div class="icon">
                <img :src="i.img" alt />
              </div>
              {{i.title}}
            </li>
          </ul>
        </div>
      </div>

      <!-- 热门问题 -->
      <div class="hot_qus_wrapper" v-if="false">
        <div class="mTitle">热门问题</div>
        <div class="content">
          <div class="hot_scroll_wrapper">
            <ul class="scroll_list">
              <li
                class="scroll-item"
                ref="sItem"
                v-for="(i,idx) in fetch_data.hot_question"
                :key="'hots_'+idx"
                v-show="i.opentype ==1"
                @click="toLink(i.link)"
              >
                <div class="img">
                  <img v-if="i.imgurl" :src="imgUrl(i.imgurl)" alt />
                </div>
                <p>{{i.titlename}}</p>
              </li>

              <li
                class="scroll-item"
                ref="sItem"
                v-for="(i,idx) in fetch_data.hot_question"
                :key="'hot_'+idx"
                v-show="i.opentype ==2"
                @click="toInfoDetail(3,i.id)"
              >
                <div class="img">
                  <img v-if="i.imgurl" :src="imgUrl(i.imgurl)" alt />
                </div>
                <p>{{i.titlename}}</p>
              </li>
            </ul>
          </div>
        </div>
      </div>

      <!-- 热门产品 -->
      <div class="hot_pro_wrapper" v-if="fetch_data.hot_goods">
        <div class="mTitle">热门产品</div>
        <div class="pro_content">
          <div
            class="product"
            v-for="(item,idx) in fetch_data.hot_goods"
            :key="'goods_'+idx"
            @click="toHotGoods(item.link)"
          >
            <img :src="imgUrl(item.imgurl)" :alt="item.titlename" class="pro_img" />
            <p class="pro_title">{{item.titlename}}</p>
          </div>
        </div>
      </div>
      <!-- 开运宝典 -->
      <div class="luck_book_wrapper" v-if="fetch_data_book">
        <div class="mTitle">开运宝典</div>
        <ul class="content">
          <!-- <li v-for="(i,idx) in fetch_data_book" :key="'book_'+idx" @click="toInfoDetail(2,i.id)"> -->
          <li
            v-for="(i,idx) in fetch_data_book"
            :key="'book_'+idx"
            @click="toInfoDetail(2,i.id,i.ios_link,i.title,i.subtitle,i.titleimg)"
          >
            <div class="c_img">
              <img :src="imgUrl(i.titleimg)" alt />
            </div>
            <div class="c_info">
              <div class="tt">
                <p class="fontHideOne">{{i.title}}</p>
                <span>{{i.looknumber}}人已看</span>
              </div>
              <p class="des">{{clipText(i.subtitle,50)}}</p>
            </div>
          </li>
        </ul>
        <loadmore v-if="isLoadMore" :tip="tip"></loadmore>
      </div>

      <div v-if="noData" class="no-data">加载完毕</div>
    </div>
  </div>
</template>

<script>
import { Swiper, SwiperItem, Scroller } from "vux";
import topHeader from "@/components/topHeader";
import roundCircle from "@/components/circle";
import loadmore from "@/components/loadMore";
import tool from "@/assets/js/tool.js";
import vconsole from "vconsole";
import { setTimeout, setInterval } from "timers";
import { parse } from "path";
import calendar from "@/components/calendar/calendar.js";
import mui from "@/assets/js/mui.min.js";
import store from "@/vuexStore/store.js/"

export default {
  name: "index",
  props: [],
  components: {
    topHeader,
    Swiper,
    SwiperItem,
    Scroller,
    roundCircle,
    loadmore
  },
  data: function() {
    return {
      swiperDuration: 5000, // 轮播停留时间
      tody_pro_list: [
        {
          img: require("../../../static/image/index/icon_jrpy@2x.png"),
          title: "今日牌运",
          pathIndex: "/brandOperationOne"
        },
        {
          img: require("../../../static/image/index/icon_jrlq@2x.png"),
          title: "每日运势",
          pathIndex: "/luckOne"
        },
        {
          img: require("../../../static/image/index/icon_cyyj@2x.png"),
          title: "穿衣指南",
          pathIndex: "/guidelines"
        }
      ],
      fetch_data: {}, //首页基本数据
      fetch_data_book: [], //开运宝典
      page_book: 1,
      isLoadMore: true,
      isFetchNext: true,
      tip: "加载更多",
      msgCount: "", //未读消息数量
      noData: false,
      showDots: true, // banner是否显示提示点
      shareIndex: undefined, //分享的索引
      refleshCircle: false,// 是否刷新今日运势图标
      uuid: this.$store.state.userID,
    };
  },
  created() {
    this.$store.commit("changePageLoading", true);
    // var vConsole = new vconsole();
    this.getDate();
    this.fetch_page();
    this.fetch_book(this.page_book);
    this.fetch_load_more();
  },
  // 如果路由进入前，是从 msgCenter页面返回来的，那么就设置当前 首页 不缓存，否则缓存
  beforeRouteEnter(to, from, next) {
    // 将上一次地址的路由存入状态机
    store.commit('setRouterPath', from.path)
    if (from.path == "/msgCenter" || from.path == "/luckOne" || from.path == "/brandOperationOne" || from.path == "/myCenter"|| from.path == "/askTeacher") {
      to.meta.keepAlive = false;
    } else {
      to.meta.keepAlive = true;
    }
    next();
  },
  // 设置跳转问大师页面缓存 
  beforeRouteLeave(to, from, next) {
    if (to.name == "h_askTeacher") {
      to.meta.keepAlive = true;
      next()
    }else{
      next();
    }
  },
  computed:{
    //首页取用户ID，必须用计算属性，其它页面直接 this.$store.state.userID
    userid() {
      // 测试uid '869115037298615,869115037349111'
      let uid = this.$store.state.userID;
      if (!uid) return;
      /* 获取未读消息*/
      this.$fetch.post("/app/Jmyc/message", { uid: uid }).then(res => {
        this.msgCount = res.data.num;
        // console.log(this.msgCount)
      });
      this.getUserInfo(uid);
      this.uuid = uid
      return this.$store.state.userID;
    }
  },
 watch: {
   uuid(newValue, oldValue){
     if(newValue){
       this.uuid = newValue
       this.refleshCircle = true
     }
   }
 }, 
  methods: {
    toLink(url, index) {
      var shareInfo = this.fetch_data.product[index];
      tool.createNavigation(this, "jmyc", url, shareInfo);
    },
    // 跳转热门产品
    toHotGoods(link) {
      tool.createNavigation(this, "hotGoods", link);
    },
    imgUrl(url) {
      return tool.imgUrl(url);
    },
    toNavgate($path, idx, params = "") {
      if (idx == 0 && window.localStorage.getItem("JMYC_USERNAME")) {
        this.$router.push("/brandOperationTwo");
        return;
      }
      if (idx == 1 && window.localStorage.getItem("JMYC_USERNAME")) {
        this.$router.push("/luckTwo");
        return;
      }
      if (params) {
        this.$router.push({
          path: $path,
          query: params
        });
      } else {
        this.$router.push({
          path: $path
        });
      }
    },
    // 跳转今日运势
    toJrys() {
      if (window.localStorage.getItem("JMYC_USERNAME")) {
        this.$router.push("/luckTwo");
      } else {
        this.$router.push("/luckOne");
      }
    },
    /**
      @func
      @desc:跳转至详情
      @param: type - 1:banner 2:开运宝典 3:热门问题  shareLink:分享链接
      @param: id - 文章id
      @param: share~~分享相关参数
    */
    // toInfoDetail(type,id){
    toInfoDetail(type, id, shareLink, shareTitle, shareContent, shareThumbs) {
      this.$router.push({
        name: "h_infoDetail",
        query: {
          type: type,
          id: id
        },
        params: {
          shareLink: shareLink,
          shareTitle: shareTitle,
          shareContent: shareContent,
          shareThumbs: this.imgUrl(shareThumbs)
        }
      });
    },
    /*截取字符串*/
    clipText(text, num) {
      return tool.clipText(text, num);
    },
    /*热门问题宽度*/
    sHotW() {
      var w = 478 + 20;
      var sHotWRem = (w / 75) * this.fetch_data.hot_question.length + "rem";
      return sHotWRem;
    },
    /* 首页数据 */
    fetch_page() {
      this.$fetch.get("/app/Jmyc/index", {}).then(res => {
        if (res.code == 200) {
          this.fetch_data = res.data;
          this.showDots = this.fetch_data.banner.length == 1 ? false : true;
          // console.log(this.fetch_data);
        }
      });
    },
    /*获取用户基本信息*/
    getUserInfo(uid) {
      this.$fetch
        .post("/app/Jmyc/user_edit", {
          // device: '869115037298615,869115037349111'
          device: uid
        })
        .then(res => {
          if (res.code == 200 && JSON.stringify(res.data) != "{}") {
            window.localStorage.JMYC_USERADRESS = [
              res.data.province,
              res.data.city,
              res.data.country
            ];
            window.localStorage.JMYC_BIRTHDATE = tool.timestampToTime(
              res.data.birthday
            );
            window.localStorage.JMYC_USERGENDER = res.data.sex;
            window.localStorage.JMYC_USERNAME = res.data.realname;
            window.localStorage.JMYC_NOPOINT = res.data.nopoint;
          }
        });
    },
    /* 首页开运宝典 */
    fetch_book(page) {
      this.$fetch.post("/app/Jmyc/Kybd", { page: page }).then(res => {
        if (res.data.length == 0) {
          this.isFetchNext = false;
          // this.tip = "没有更多数据了";
          this.noData = true;
          this.isLoadMore = false;
          return;
        }
        if (res.code == 200) {
          if (page == 1) {
            this.fetch_data_book = res.data;
          } else {
            this.fetch_data_book = [...this.fetch_data_book, ...res.data];
            // this.fetch_data_book = this.fetch_data_book.concat(res.data);
          }
          if (res.data.length < 6) {
            // this.tip = "没有更多数据了";
            this.isFetchNext = false;
            this.noData = true;
            this.isLoadMore = false;
            return;
          }
          this.$store.commit("changePageLoading", false);
        }
      });
    },
    /* 加载更多*/
    fetch_load_more() {
      window.onscroll = () => {
        //变量scrollTop是滚动条滚动时，距离顶部的距离
        var scrollTop =
          document.documentElement.scrollTop || document.body.scrollTop;
        //变量windowHeight是可视区的高度
        var windowHeight =
          document.documentElement.clientHeight || document.body.clientHeight;
        //变量scrollHeight是滚动条的总高度
        var scrollHeight =
          document.documentElement.scrollHeight || document.body.scrollHeight;
        //滚动条到底部的条件
        if (scrollTop + windowHeight == scrollHeight) {
          this.page_book++;
          if (this.isFetchNext) {
            this.isLoadMore = true; //显示loadMore组件
            this.fetch_book(this.page_book);
          }
          //写后台加载数据的函数
          // console.log("距顶部"+scrollTop+"可视区高度"+windowHeight+"滚动条总高度"+scrollHeight);
        }
      };
    },
    /* 路由至消息中心 */
    toMsgCenter() {
      var msgCount = this.msgCount;
      this.$router.push({
        path: "/msgCenter",
        query: {
          msgCount: msgCount
        }
      });
    },
    /* 获取今日时间 */
    getDate() {
      var date = new Date();
      var y = date.getFullYear(); //年
      var m = date.getMonth() + 1; //月
      var d = date.getDate(); //日
      var w = date.getDay(); //星期
      var weeks = ["日", "一", "二", "三", "四", "五", "六"];
      var lunarObj = calendar.solar2lunar(y, m, d);
      var curweek = weeks[w];
      var today = `${m}月${d}日 (星期${curweek}) 农历${lunarObj.IMonthCn}${lunarObj.IDayCn}`;
      return today;
    }
  }
};
</script>

<style lang="less">
@import "../../assets/css/public.less";
@import "../../assets/css/tml_base.less";
@import "./index.less";
</style>
